<template>
  <el-form v-bind="getBindValue" :model="formModel" ref="formElRef">
    <el-row v-bind="getRow">
      <el-col
        v-bind="getCol"
        v-for="schema in getSchema"
        :key="schema.field"
        :span="getHidden(schema) ? 0 : getCol.span"
      >
        <el-form-item
          v-bind="schema"
          :label="schema.label"
          :prop="schema.field"
          :showFeedback="schema.showFeedback"
          v-if="!getHidden(schema)"
        >
          <!--标签名右侧温馨提示-->
          <template #label v-if="schema.labelMessage">
            <div class="flex items-center">
              {{ schema.label }}
              <el-tooltip
                trigger="hover"
                :style="schema.labelMessageStyle"
                :content="schema.labelMessage"
              >
                <el-icon size="18" class="ml-1 text-gray-400 cursor-pointer el-input__icon">
                  <QuestionCircleOutlined />
                </el-icon>
              </el-tooltip>
            </div>
          </template>

          <!--判断插槽-->
          <template v-if="schema.slot">
            <slot
              :name="schema.slot"
              :model="formModel"
              :prop="schema.field"
              :value="formModel[schema.field]"
            ></slot>
          </template>

          <!--NCheckbox-->
          <template v-else-if="schema.component === 'Checkbox'">
            <el-checkbox-group
              v-bind="getSpecComponentProps(schema)"
              v-model="formModel[schema.field]"
              :class="{ isFull: schema.isFull != false && getProps.isFull }"
            >
              <el-space>
                <el-checkbox
                  v-for="item in schema.componentProps?.options"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.label }}
                </el-checkbox>
              </el-space>
            </el-checkbox-group>
          </template>

          <!--elRadioGroup-->
          <template v-else-if="schema.component === 'RadioGroup'">
            <el-radio-group
              v-bind="getSpecComponentProps(schema)"
              v-model="formModel[schema.field]"
              :class="{ isFull: schema.isFull != false && getProps.isFull }"
            >
              <el-space>
                <el-radio
                  v-for="item in schema.componentProps?.options"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-space>
            </el-radio-group>
          </template>

          <!--elSelect-->
          <template v-else-if="schema.component === 'Select'">
            <el-select
              v-bind="getSpecComponentProps(schema)"
              v-model="formModel[schema.field]"
              :class="{ isFull: schema.isFull != false && getProps.isFull }"
            >
              <el-option
                v-for="item in schema.componentProps?.options"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </template>

          <!--BasicSelect-->
          <template v-else-if="schema.component === 'BasicSelect'">
            <Select v-bind="getSpecComponentProps(schema)" v-model="formModel[schema.field]" />
          </template>

          <!--动态渲染表单组件-->
          <component
            v-else
            v-bind="getComponentProps(schema)"
            :is="`el-${schema.component}`"
            v-model="formModel[schema.field]"
          />
          <!--组件后面的内容-->
          <template v-if="schema.suffix">
            <slot
              :name="schema.suffix"
              :model="formModel"
              :prop="schema.field"
              :value="formModel[schema.field]"
            ></slot>
          </template>
        </el-form-item>
      </el-col>
      <!--提交 重置 展开 收起 按钮-->
      <el-col :span="8" v-if="getProps.showActionButtonGroup">
        <el-form-item :label-width="isHorizontal ? '20px' : getProps.labelWidth">
          <el-space>
            <el-button
              v-if="getProps.showSubmitButton"
              v-bind="getSubmitBtnOptions"
              @click="handleSubmit"
              :loading="loadingSub"
              >{{ getProps.submitButtonText }}</el-button
            >
            <el-button
              v-if="getProps.showResetButton"
              v-bind="getResetBtnOptions"
              @click="resetFields"
              >{{ getProps.resetButtonText }}</el-button
            >
            <!-- <el-button
            type="primary"
            link
            icon-placement="right"
            v-if="isHorizontal  && getProps.showAdvancedButton"
            @click="unfoldToggle"
          >
            <template #icon>
              <el-icon size="14" class="el-input__icon unfold-icon" v-if="overflow">
                <DownOutlined />
              </el-icon>
              <el-icon size="14" class="el-input__icon unfold-icon" v-else>
                <UpOutlined />
              </el-icon>
            </template>
            {{ overflow ? '展开' : '收起' }}
          </el-button> -->
          </el-space>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script lang="ts" setup>
  import { reactive, ref, useAttrs, computed, unref, onMounted, watch } from 'vue';

  // 导入自定义工具函数和钩子
  import { createPlaceholderMessage } from './helper';
  import { useFormEvents } from './hooks/useFormEvents';
  import { useFormValues } from './hooks/useFormValues';
  import { Select } from '@/design/components/Select';

  // 导入props定义和图标组件
  import { basicProps } from './props';
  import { QuestionCircleOutlined } from '@vicons/antd';

  // 导入类型定义和工具函数
  import type { Ref } from 'vue';
  import type { FormSchema, FormProps, FormActionType } from './types/form';
  import { isArray, isBoolean, isFunction } from '@/utils/is/index';
  import { deepMerge } from '@/utils';

  // 使用defineProps和defineEmits定义组件的props和emits
  const props = defineProps({ ...basicProps });
  const emit = defineEmits(['reset', 'submit', 'register', 'advanced']);
  const attrs = useAttrs();

  // 定义响应式引用和计算属性
  const defaultFormModel = ref<Recordable>({});
  const formModel = reactive<Recordable>({});
  const propsRef = ref<Partial<FormProps>>({});
  const schemaRef = ref<Nullable<FormSchema[]>>(null);
  const formElRef = ref<Nullable<FormActionType>>(null);
  // const gridCollapsed = ref(!props.collapsed);
  const loadingSub = ref(false);
  const isUpdateDefaultRef = ref(false);

  // 创建计算属性，用于获取提交按钮和重置按钮的配置
  const getSubmitBtnOptions = computed(() => {
    return Object.assign(
      {
        size: props.size,
        type: 'primary',
      },
      props.submitButtonOptions,
    );
  });

  const getResetBtnOptions = computed(() => {
    return Object.assign(
      {
        size: props.size,
        type: 'default',
      },
      props.resetButtonOptions,
    );
  });

  // 定义辅助函数，用于获取表单组件的props
  function getComponentProps(schema) {
    const compProps = schema.componentProps ?? {};
    const component = schema.component;
    return {
      class: schema.isFull != false && getProps.value.isFull ? 'w-full' : '',
      clearable: true,
      placeholder: createPlaceholderMessage(unref(component)),
      ...compProps,
    };
  }

  // 定义辅助函数，用于判断表单项是否隐藏
  function getHidden(schema): boolean {
    const hidden = schema.hidden;
    const field = schema.field;
    if (isBoolean(hidden)) return hidden;

    if (isFunction(hidden)) {
      const values = getFieldsValue();
      const status = hidden({ schema, values, model: formModel, field });
      return status;
    }
    return false;
  }

  // 定义辅助函数，用于获取特定组件的props
  function getSpecComponentProps(schema) {
    const compProps = schema.componentProps ?? {};
    return {
      ...compProps,
    };
  }

  // 创建计算属性，用于获取表单props
  const getProps = computed((): FormProps => {
    const formProps = { ...props, ...unref(propsRef) } as FormProps;
    const rulesObj: any = {
      rules: {},
    };
    const schemas: any = formProps.schemas || [];
    schemas.forEach((item) => {
      if (item.rules && isArray(item.rules)) {
        rulesObj.rules[item.field] = item.rules;
      }
    });
    return { ...formProps, ...unref(rulesObj) };
  });

  // 创建计算属性，用于判断布局是否为水平
  const isHorizontal = computed(() => {
    const { layout } = unref(getProps);
    return layout === 'horizontal';
  });

  // 创建计算属性，用于获取row的props
  const getRow = computed(() => {
    const { rowProps } = unref(getProps);
    return {
      ...rowProps,
      // collapsed: isHorizontal .value ? gridCollapsed.value : false,
      // responsive: 'screen',
    };
  });

  // 创建计算属性，用于获取col的props
  const getCol = computed(() => {
    const { colProps } = unref(getProps);
    return {
      ...colProps,
      // collapsed: isHorizontal .value ? gridCollapsed.value : false,
      // responsive: 'screen',
    };
  });

  // 创建计算属性，用于获取表单的bindValue
  const getBindValue = computed(() => ({ ...attrs, ...props, ...unref(getProps) } as Recordable));

  // 创建计算属性，用于获取表单项配置
  const getSchema = computed((): FormSchema[] => {
    const schemas: FormSchema[] = unref(schemaRef) || (unref(getProps).schemas as any);
    for (const schema of schemas) {
      const { defaultValue } = schema;
      // handle date type
      // dateItemType.includes(component as string)
      if (defaultValue) {
        schema.defaultValue = defaultValue;
      }
    }
    return schemas as FormSchema[];
  });

  // 使用自定义钩子处理表单值和事件
  const { handleFormValues, initDefault } = useFormValues({
    defaultFormModel,
    getSchema,
    formModel,
  });

  // 使用自定义钩子处理表单提交、重置、验证等事件
  const { handleSubmit, validate, resetFields, getFieldsValue, clearValidate, setFieldsValue } =
    useFormEvents({
      emit,
      getProps,
      formModel,
      getSchema,
      formElRef: formElRef as Ref<FormActionType>,
      defaultFormModel,
      loadingSub,
      handleFormValues,
    });

  // function unfoldToggle() {
  //   gridCollapsed.value = !gridCollapsed.value;
  //   emit('advanced', gridCollapsed.value);
  // }

  // 定义辅助函数，用于设置表单props
  async function setProps(formProps: Partial<FormProps>): Promise<void> {
    propsRef.value = deepMerge(unref(propsRef) || {}, formProps);
  }

  // 定义辅助函数，用于更新loading状态
  function setLoadingSub(status: boolean): void {
    loadingSub.value = status;
  }

  // 定义表单行为类型
  const formActionType: Partial<FormActionType> = {
    getFieldsValue,
    setFieldsValue,
    resetFields,
    validate,
    clearValidate,
    setProps,
    setLoadingSub,
    submit: handleSubmit,
  };

  // 使用watch监听表单项配置变化，并初始化默认值
  watch(
    () => getSchema.value,
    (schema) => {
      if (unref(isUpdateDefaultRef)) {
        return;
      }
      if (schema?.length) {
        initDefault();
        isUpdateDefaultRef.value = true;
      }
    },
  );

  // 在组件挂载后初始化默认值，并注册表单行为
  onMounted(() => {
    initDefault();
    emit('register', formActionType);
  });

  // 使用defineExpose将表单行为类型暴露给外部
  defineExpose({
    ...formActionType,
  });
</script>

<style lang="scss" scoped>
  .isFull {
    width: 100%;
    justify-content: flex-start;
  }

  .unfold-icon {
    display: flex;
    align-items: center;
    height: 100%;
    margin-left: -3px;
  }
</style>
